package com.blue.service.impl;

import com.blue.mapper.AccountMapper;
import com.blue.pojo.Account;
import com.blue.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Locale;

@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public int insert(Account account) {
        return accountMapper.insert(account);
    }

    @Override
    public int deleteByActno(String actno) {
        return accountMapper.deleteByActno(actno);
    }

    @Override
    public int update(Account account) {
        return accountMapper.update(account);
    }

    @Override
    public Account selectByActno(String actno) {
        return accountMapper.selectByActno(actno);
    }

    @Override
    public List<Account> selectAll() {
        return accountMapper.selectAll();
    }

    @Override
    public void transfer(String fromActno, String toActno, Double money) {
        Account fromAct = accountMapper.selectByActno(fromActno);
        Account toAct = accountMapper.selectByActno(toActno);

        if (fromAct.getBalance() < money) {
            throw new RuntimeException("转出账号余额不足!");
        }

        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);

        int count = 0;

        count += accountMapper.update(fromAct);
//        String str = null;
//        str.toString();
        count += accountMapper.update(toAct);

        if (count != 2) {
            throw new RuntimeException("转账失败!");
        }
    }
}
